﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Gueei.Gallery.Core.DisplayProfiles;
using Gueei.Gallery.Core.Repositories;
using Gueei.Gallery.Core.ViewModels;
using Gueei.Gallery.Web.ViewModels;

namespace Gueei.Gallery.Web.Extensions
{
	public static class ImageThumbHtmlExtension
	{
		public static HtmlString Image(this HtmlHelper helper, ImageViewModel model, string profileName = null)
		{
			var tb = new TagBuilder("img");
			tb.MergeAttribute("src", "/image/get?id=" + model.Id + "&l=" + model.LastModified.Ticks + "&profile=" + profileName);
			tb.MergeAttribute("title", model.Name);
			tb.MergeAttribute("alt", model.Name);
			return new HtmlString(tb.ToString(TagRenderMode.SelfClosing));
		}

		public static HtmlString ImageThumb(this HtmlHelper helper, ImageViewModel model, 
			string thumbProfileName = DefaultProfileName.Thumbsize, string fullSizeProfile = DefaultProfileName.Fullsize)
		{
			string link = UrlHelper.GenerateUrl(null, "get", "image",
				new RouteValueDictionary { { "id", model.Id }, { "profile", fullSizeProfile } },
				helper.RouteCollection,
				helper.ViewContext.RequestContext, false);
			return ImageThumb(helper, link, model, thumbProfileName);
		}

		public static HtmlString ImageThumb(this HtmlHelper helper, string link, ImageViewModel model, 
			string thumbProfileName = DefaultProfileName.Thumbsize)
		{
			var linkTb = new TagBuilder("a");
			linkTb.InnerHtml = "<span></span>" + Image(helper, model, thumbProfileName).ToString();
			linkTb.MergeAttribute("href", link);
			linkTb.MergeAttribute("title", model.Name);
			linkTb.MergeAttribute("rel", "gallery");
			return new HtmlString(linkTb.ToString());
		}

		public static string ImageDetailLink(this HtmlHelper helper, ImageViewModel model)
		{
			return UrlHelper.GenerateUrl(null, "view", "image", 
				new RouteValueDictionary{ {"id", model.Id}}, 
				helper.RouteCollection, helper.ViewContext.RequestContext,
								  false);
		}

		public static HtmlString DownloadImageLink(this HtmlHelper helper, string linkText, 
			ImageViewModel model, string profileName=null)
		{
			var linkTb = new TagBuilder("a");
			linkTb.InnerHtml = linkText;
			linkTb.MergeAttribute("href", "/image/get?id=" + model.Id + "&profile=" + profileName);
			linkTb.MergeAttribute("title", model.Name);
			return new HtmlString(linkTb.ToString());
		}

		public static HtmlString ImageEditor(this HtmlHelper helper, ImageEditViewModel model, string profileName=null)
		{
			var tb = new TagBuilder("img");
			tb.MergeAttribute("src", "/image/get?id=" + model.Id + 
				 "&profile=" + profileName);
			tb.MergeAttribute("title", model.Name);
			tb.MergeAttribute("alt", model.Name);
			return new HtmlString(tb.ToString(TagRenderMode.SelfClosing));
		}
	}
}